﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using PeachLite.Helpers;
using PeachLite.Entity;
using PeachLite.Entity.Admin;
using System.IO;
using System.Data;
using System.Text;

namespace PeachLite.Admin.X
{
    /// <summary>
    /// Ajax服务器处理程序
    /// </summary>
    public class Ajax : AjaxBase
    {
        private const string TIME_FORMAT = "yyyyMMddHHmmssfff";
        private const string TIME_FORMAT1 = "yyyyMMdd";
        private const string TIME_FORMAT2 = "yyyyMMddHHmmss";
        private static string FILIST_FORMAT = "<li  p='{4}' type='{6}'><dl><dt><a title='{3}' onclick='{5}'><img src='{0}' alt='{2}' /></a><span class='del' onclick='FileManger.deleteFile(this);'>×</span></dt><dd>{1}</dd></dl></li>";
        private static string FILIST_FORMAT2 = "<li><dl><dt p='{4}'><a title='{3}' {5}><img src='{0}' alt='{2}' /></a><span class='del' onclick='del(this);'>×</span></dt><dd>{1}</dd></dl></li>";

        #region 方法

        protected override SysMessage Do(int code)
        {
            SysMessage m;
            if (code != -1)
            {
                switch (code)
                {
                    case 101001:
                        m = Login(Context);
                        break;
                    case 111001:
                        m = GetUser(Context);
                        break;
                    case 111002:
                        m = Quit(Context);
                        break;
                    case 111003:
                        m = ResetPassword(Context);
                        break;
                    case 111101:
                        m = SaveClass(Context);
                        break;
                    case 111102:
                        m = DeleteClass(Context);
                        break;
                    case 111201:
                        m = CheckImage(Context);
                        break;
                    case 111202:
                        m = DeleteArticle(Context);
                        break;
                    case 111203:
                        m = SaveArticle(Context);
                        break;
                    case 111204:
                        m = SaveImage(Context);
                        break;
                    case 111205:
                        m = DeleteImage(Context);
                        break;
                    case 111301:
                        m = DeleteFile(Context);
                        break;
                    case 111302:
                        m = GetFileList(Context);
                        break;
                    case 111303:
                        m = FiUploader(Context);
                        break;
                    case 111304:
                        m = NewFolder(Context);
                        break;
                    case 111305:
                        m = CheckFolder(Context);
                        break;
                    case 111306:
                        m = FiUploaderM(Context);
                        break;
                    default:
                        m = new SysMessage();
                        m.Success = false;
                        m.Message = "业务代码有误";
                        break;
                }
            }
            else
            {
                m = new SysMessage();
                m.Success = false;
                m.Message = "业务代码有误";
            }
            return m;
        }

        /// <summary>
        /// 获取用户登录信息
        /// </summary>
        /// <param name="context"></param>
        private SysMessage GetUser(HttpContext context)
        {
            SysMessage m = new SysMessage();

            if (Admin.AID >= 0)
            {
                m.Success = true;
                m.O = new { AdminId = Admin.AdminId };
            }
            else
            {
                m.Success = false;
                ////m.Url = "/admin/login.aspx";
            }
            return m;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private SysMessage Login(HttpContext context)
        {
            SysMessage m = new SysMessage();
            if (Admin.IsLogin)
            {
                m.Success = true;
                m.Url = "index.aspx";
                m.O = new { AdminId = Admin.AdminId };
                return m;
            }

            string n = context.Request.Form["n"] == null ? "" : context.Request.Form["n"].Trim();
            string p = context.Request.Form["p"] == null ? "" : context.Request.Form["p"].Trim();


            //判断用户名和密码是否为空
            if (n == "" || p == "")
            {
                m.Success = false;
                m.Message = "用户名和密码不能为空！";
                return m;
            }

            string sql = "sp_Admin_Ajax_Login '" + n + "','" + p.ToUpper() + "','" + context.Request.UserHostAddress + "'";
            SysResult r = SqlHelper.Execute(sql);

            if (r.Success)
            {
                Admin.AID = int.Parse(r.Data["ID"].ToString());
                Admin.AdminId = r.Data["Name"].ToString();
                Admin.AdminName = r.Data["Name"].ToString();
                Admin.IsLogin = true;
                m.Code = 0;
                m.Success = true;
                m.Url = "index.aspx";
            }
            else
            {
                m.Success = false;
                m.Message = r.Message;
            }
            return m;
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <param name="context"></param>
        private SysMessage Quit(HttpContext context)
        {
            Admin = new AdminAccount();
            SysMessage m = new SysMessage();
            m.Code = 0;
            m.Success = true;
            m.Url = "login.aspx";
            return m;
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        private SysMessage ResetPassword(HttpContext context)
        {
            SysMessage m = new SysMessage();
            string pwd1 = context.Request.Form["pwd1"] == null ? "" : context.Request.Form["pwd1"].Trim().ToUpper();    //旧密码
            string pwd2 = context.Request.Form["pwd2"] == null ? "" : context.Request.Form["pwd2"].Trim().ToUpper();    //新密码

            if (pwd1 == "" || pwd2 == "")
            {
                m.Success = false;
                m.Message = "旧密码和新密码不能为空！";
                return m;
            }

            string sql = "sp_Admin_Ajax_ResetPWD '" + Admin.AdminId + "','" + pwd1 + "','" + pwd2 + "','" + context.Request.UserHostAddress + "'";
            SysResult r = SqlHelper.Execute(sql);
            if (r.Success)
            {
                m.Code = 0;
                m.Success = true;
                m.Message = "修改密码成功！";
            }
            else
            {
                m.Success = false;
                m.Message = r.Message;
            }
            return m;
        }

        /// <summary>
        /// 保存栏目修改
        /// </summary>
        /// <param name="context"></param>
        private SysMessage SaveClass(HttpContext context)
        {
            SysMessage m = new SysMessage();
            string cid = context.Request.Form["cid"] == null ? "" : context.Request.Form["cid"].Trim();
            string name = context.Request.Form["name"] == null ? "" : context.Request.Form["name"].Trim();
            string ordinal = context.Request.Form["ordinal"] == null ? "" : context.Request.Form["ordinal"].Trim();
            string desc = context.Request.Form["desc"] == null ? "" : context.Request.Form["desc"].Trim();

            //校验栏目id
            if (cid == "")
            {
                cid = BizHelper.GetSerial(1);
            }
            else
            {
                try
                {
                    cid = long.Parse(cid).ToString();
                }
                catch
                {
                    m.Success = false;
                    m.Message = "栏目id数据类型有误！";
                    return m;
                }
            }

            //校验栏目名称
            if (name == "")
            {
                m.Success = false;
                m.Message = "栏目名称不能为空！";
                return m;
            }

            //交易序号
            if (ordinal == "")
            {
                ordinal = "0";
            }
            else
            {
                try
                {
                    ordinal = int.Parse(ordinal).ToString();
                }
                catch
                {
                    m.Success = false;
                    m.Message = "序号数据类型有误！";
                    return m;
                }
            }

            string sql = "sp_Admin_Ajax_SaveClass " + cid + ",'" + name + "'," + ordinal + ",'" + desc + "'";
            SysResult r = SqlHelper.Execute(sql);
            if (r.Success)
            {
                m.Code = 0;
                m.Success = true;
                m.Message = r.Message;
                m.Url = "classlist.aspx";
                m.O = new { CID = r.Data["CID"].ToString() };
            }
            else
            {
                m.Success = false;
                m.Message = r.Message;
            }
            return m;
        }

        /// <summary>
        /// 删除栏目
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private SysMessage DeleteClass(HttpContext context)
        {
            SysMessage m = new SysMessage();

            string cid = context.Request.Form["cid"] == null ? "" : context.Request.Form["cid"].Trim();
            //判断栏目编号是否为空
            if (cid == "")
            {
                m.Success = false;
                m.Message = "栏目编号不能为空！";
                return m;
            }
            //检查栏目编号是否为long型
            try
            {
                cid = long.Parse(cid).ToString();
            }
            catch (Exception e)
            {
                m.Success = false;
                m.Message = "栏目ID数据类型有误！详细信息:" + e.Message;
                return m;
            }

            string sql = "sp_Admin_Ajax_DeleteClass " + cid;
            SysResult r = SqlHelper.Execute(sql);
            if (r.Success)
            {
                m.Code = 0;
                m.Success = true;
                m.Message = "删除栏目成功！";
            }
            else
            {
                m.Success = false;
                m.Code = r.Code;
                m.Message = r.Message;
            }
            return m;
        }

        /// <summary>
        /// 上传临时图片文件
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private SysMessage CheckImage(HttpContext context)
        {
            SysMessage m = new SysMessage();
            string[] extensions = { ".jpg", ".jpeg", ".png", ".gif" };
            //获得空间名（name）
            string id = context.Request.Form["id"] == null ? "" : context.Request.Form["id"].Trim();
            if (id == "")
            {
                m.Success = false;
                m.Message = "file控件名为空!";
                return m;
            }
            //获得file控件
            HttpPostedFile file = context.Request.Files[id];

            //检查控件是否为空
            if (file == null)
            {
                m.Success = false;
                m.Message = "名为" + id + "的file控件为空！";
                return m;
            }
            string fileName = file.FileName;

            //检查文件是否为空
            if (string.IsNullOrWhiteSpace(fileName))
            {
                m.Success = false;
                m.Message = "文件为空！";
                return m;
            }
            //检查文件是否有扩展名
            if (!Path.HasExtension(fileName))
            {
                m.Success = false;
                m.Message = "文件格式有误！";
                return m;
            }

            string fileExtension = Path.GetExtension(fileName).ToLower();

            //检查文件是否为图片文件
            bool fileOK = false;
            foreach (string ex in extensions)
            {
                if (fileExtension == ex)
                {
                    fileOK = true;
                    break;
                }
            }
            if (!fileOK)
            {
                m.Success = false;
                m.Message = "选择的文件不是图片文件！";
                return m;
            }

            //检查保存路径是否有误
            try
            {
                string filePath = context.Server.MapPath(ConfigHelper.Config.FileTempPath);
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                string name = DateTime.Now.ToString(TIME_FORMAT) + fileExtension;
                file.SaveAs(filePath + name);
                m.Success = true;
                m.Url = ConfigHelper.Config.FileTempPath + name;
            }
            catch (Exception ex)
            {
                m.Success = false;
                m.Message = ex.Message;
            }
            return m;
        }

        /// <summary>
        /// 删除文章
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private SysMessage DeleteArticle(HttpContext context)
        {
            SysMessage m = new SysMessage();

            string aid = context.Request.Form["aid"] == null ? "" : context.Request.Form["aid"].Trim();
            if (aid == "")
            {
                m.Success = false;
                m.Message = "删除文章失败：文章编号为空！";
                return m;
            }
            try
            {
                aid = long.Parse(aid).ToString();
            }
            catch
            {
                m.Success = false;
                m.Message = "删除文章失败：文章编号数据类型有误!";
            }
            string sql = "sp_Admin_Ajax_DeleteArticle " + aid;

            SysResult r = SqlHelper.Execute(sql);
            if (r.Success)
            {
                m.Success = true;
                m.Code = 0;
                m.Message = "删除成功！";
                m.Url = "articlelist.aspx";
            }
            else
            {
                m.Success = false;
                m.Code = r.Code;
                m.Message = r.Message;
            }

            return m;
        }

        /// <summary>
        /// 添加/保存文章
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private SysMessage SaveArticle(HttpContext context)
        {
            SysMessage m = new SysMessage();
            //获得提交信息
            string aid = context.Request.Form["aid"] == null ? "" : context.Request.Form["aid"].Trim();      //文章编码
            string atit = context.Request.Form["atit"] == null ? "" : context.Request.Form["atit"].Trim();   //文章标题
            string tsub = context.Request.Form["tsub"] == null ? "" : context.Request.Form["tsub"].Trim();    //副标题
            string cid = context.Request.Form["cid"] == null ? "" : context.Request.Form["cid"].Trim();                                           //文章栏目id
            string ordinal = context.Request.Form["ordinal"] == null ? "1" : context.Request.Form["ordinal"].Trim(); //文章序号
            string author = context.Request.Form["author"] == null ? "" : context.Request.Form["author"].Trim();      //作者
            string source = context.Request.Form["source"] == null ? "" : context.Request.Form["source"].Trim();      //来源
            string ctime = context.Request.Form["ctime"] == null ? "" : context.Request.Form["ctime"].Trim();       //创作时间
            string rdurl = context.Request.Form["rdurl"] == null ? "" : context.Request.Form["rdurl"].Trim();         //链接
            string timg = context.Request.Form["timg"] == null ? "" : context.Request.Form["timg"].Trim();    //标题图片
            string key = context.Request.Form["key"] == null ? "" : context.Request.Form["key"].Trim();            //关键字
            string desc = context.Request.Form["desc"] == null ? "" : context.Request.Form["desc"].Trim();    //描述
            string sumy = context.Request.Form["sumy"] == null ? "" : context.Request.Form["sumy"].Trim();              //摘要
            string content = context.Request.Form["content"] == null ? "" : context.Request.Form["content"].Trim();          //文章内容

            //检查文章编号数据类型
            if (aid == "")
            {
                aid = BizHelper.GetSerial(1);
            }
            else
            {
                try
                {
                    aid = long.Parse(aid).ToString();
                }
                catch
                {
                    m.Success = false;
                    m.Message = "文章编号数据类型有误！";
                    return m;
                }
            }

            //检查文章标题是否为空
            if (atit == "")
            {
                m.Success = false;
                m.Message = "文章标题不能为空！";
                return m;

            }

            //检查文章栏目id是否为空
            if (cid == "")
            {
                m.Success = false;
                m.Message = "所属栏目不能为空！";
                return m;
            }
            try
            {
                cid = long.Parse(cid).ToString();
            }
            catch
            {
                m.Success = false;
                m.Message = "栏目id数据类型有误！";
                return m;
            }

            //检查创作时间是否为有效的日期格式
            if (ctime != "")
            {
                try
                {
                    DateTime d = DateTime.Parse(ctime);
                }
                catch
                {
                    m.Success = false;
                    m.Message = "创造时间不是有效的日期格式！";
                    return m;
                }
            }

            //检查文章序号是否为int型
            try
            {
                ordinal = int.Parse(ordinal).ToString();
            }
            catch
            {
                m.Success = false;
                m.Message = "文章序号数据类型有误！";
                return m;
            }

            //保存标题图片
            string tpn = "";
            if (timg != "" && timg.ToLower().IndexOf(ConfigHelper.Config.DefaultImage) < 0)
            {
                tpn = ConfigHelper.Config.TitleImagePath + Path.GetFileName(timg);
                string p = context.Server.MapPath(ConfigHelper.Config.TitleImagePath) + Path.GetFileName(timg);
                if (!File.Exists(p))
                {
                    string tempPath = context.Server.MapPath(timg);     //临时图片文件路径
                    if (!File.Exists(tempPath))
                    {
                        m.Success = false;
                        m.Message = "标题图片文件不存在，请重新上传！";
                        return m;
                    }
                    try
                    {
                        File.Copy(tempPath, p, false);
                    }
                    catch (Exception ex)
                    {
                        m.Success = false;
                        m.Message = ex.Message;
                        return m;
                    }
                }
            }

            //更新数据库
            string sql = "sp_Admin_Ajax_SaveArticle " + aid + "," + cid + ",'" + atit + "','" + tsub + "','" + tpn + "'," + ordinal + ",'" + author + "','" + source + "','" + ctime + "','" + rdurl + "','" + key + "','" + desc + "','" + sumy + "','" + content + "','" + Admin.AID + "'";

            SysResult r = SqlHelper.Execute(sql);
            if (r.Success)
            {
                m.Success = true;
                m.Code = 0;
                m.Message = r.Message;
                m.Url = "articlelist.aspx";
                m.O = new { AID = r.Data["AID"].ToString(), TitleImage = tpn };
            }
            else
            {
                m.Success = false;
                m.Code = r.Code;
                m.Message = r.Message;
            }
            return m;
        }

        /// <summary>
        /// 添加/保存相关图片
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private SysMessage SaveImage(HttpContext context)
        {
            SysMessage m = new SysMessage();

            string aid = context.Request.Form["aid"] == null ? "" : context.Request.Form["aid"].Trim();     //文章编号
            string pid = context.Request.Form["pid"] == null ? "" : context.Request.Form["pid"].Trim();     //图片编号
            string psrc = context.Request.Form["psrc"] == null ? "" : context.Request.Form["psrc"].Trim();  //图片地址
            string ptit = context.Request.Form["ptit"] == null ? "" : context.Request.Form["ptit"].Trim();  //图片标题
            string pdes = context.Request.Form["pid"] == null ? "" : context.Request.Form["pdes"].Trim();   //图片描述
            string pod = context.Request.Form["pod"] == null ? "1" : context.Request.Form["pod"].Trim();    //图片序号
            string name;
            string extension;

            //校验文章id
            if (aid == "")
            {
                m.Success = false;
                m.Message = "文章编号不能为空，请创建文章基础信息后再添加相关图片！";
                return m;
            }
            try
            {
                aid = long.Parse(aid).ToString();
            }
            catch (Exception ex)
            {
                m.Success = false;
                m.Message = "文章编号数据类型有误：" + ex.Message;
                return m;
            }

            //如果图片为空则退出
            if (psrc == "" || psrc.ToLower().IndexOf("none_80.jpg") > -1)
            {
                m.Success = false;
                m.Message = "图片不能为空！";
                return m;

            }

            //校验图片序号
            try
            {
                pod = int.Parse(pod).ToString();
            }
            catch (Exception ex)
            {
                m.Success = false;
                m.Message = "图片序号数据类型有误：" + ex.Message;
                return m;
            }

            extension = Path.GetExtension(psrc).ToLower();
            string temp = context.Server.MapPath(psrc);
            if (pid == "")
            {
                pid = BizHelper.GetSerial(1);
                name = pid;
                string p = context.Server.MapPath(ConfigHelper.Config.ArticleImagePath) + pid + extension;
                try
                {
                    File.Copy(temp, p, false);
                }
                catch (Exception ex)
                {
                    m.Success = false;
                    m.Message = ex.Message;
                    return m;
                }
            }
            else
            {
                //校验图片编号
                try
                {
                    pid = long.Parse(pid).ToString();
                }
                catch (Exception ex)
                {
                    m.Success = false;
                    m.Message = "图片编号数据类型有误：" + ex.Message;
                    return m;
                }
                //判断是否需要跟新图片
                if (Path.GetFileName(psrc).ToLower() == pid + extension)
                {
                    name = pid;
                }
                else
                {
                    name = BizHelper.GetSerial(1);
                    //重新保存图片
                    string p = context.Server.MapPath(ConfigHelper.Config.ArticleImagePath) + name + extension;
                    try
                    {
                        File.Copy(temp, p, false);
                    }
                    catch (Exception ex)
                    {
                        m.Success = false;
                        m.Message = ex.Message;
                        return m;
                    }
                }
            }

            string sql = "sp_Admin_Ajax_SaveImage " + aid + "," + pid + ",'" + name + "','" + extension + "','" + ptit + "','" + pdes + "','" + ConfigHelper.Config.ArticleImagePath + "'," + pod;
            SysResult r = SqlHelper.Execute(sql);
            if (r.Success)
            {
                m.Code = 0;
                m.Success = true;
                m.Message = r.Message;
                m.O = new { PID = name, Src = ConfigHelper.Config.ArticleImagePath + name + extension, Title = ptit, Desc = pdes, Ordinal = pod };
            }
            else
            {
                m.Success = false;
                m.Code = r.Code;
                m.Message = r.Message;
            }
            return m;
        }

        /// <summary>
        /// 删除相关图片
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private SysMessage DeleteImage(HttpContext context)
        {
            SysMessage m = new SysMessage();
            string aid = context.Request.Form["aid"] == null ? "" : context.Request.Form["aid"].Trim();
            string pid = context.Request.Form["pid"] == null ? "" : context.Request.Form["pid"].Trim();
            long t;
            if (aid == "" || !long.TryParse(aid, out t))
            {
                m.Code = 1;
                m.Success = false;
                m.Message = "文章编码有误！";
                return m;
            }
            if (pid == "" || !long.TryParse(pid, out t))
            {
                m.Code = 2;
                m.Success = false;
                m.Message = "图片编码有误！";
                return m;
            }

            string sql = "sp_Admin_Ajax_DeleteImage " + aid + "," + pid;
            SysResult r = SqlHelper.Execute(sql);
            if (r.Success)
            {
                m.Code = 0;
                m.Success = true;
            }
            else
            {
                m.Success = false;
                m.Code = r.Code;
                m.Message = r.Message;
            }
            return m;
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private SysMessage DeleteFile(HttpContext context)
        {
            SysMessage m = new SysMessage();
            string p = context.Request.Form["p"] == null ? "" : context.Request.Form["p"].Trim();
            if (p == "")
            {
                m.Code = 1;
                m.Success = false;
                m.Message = "路径为空！";
                return m;
            }

            m = FileHelper.DeleteFile(context.Server.MapPath(p));
            return m;
        }

        /// <summary>
        /// 获得文件列表
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private SysMessage GetFileList(HttpContext context)
        {
            SysMessage m = new SysMessage();

            string path = context.Request.Form["p"] == null ? "" : context.Request.Form["p"].Trim();
            string root = context.Request.Form["root"] == null ? "" : context.Request.Form["root"].Trim();
            path = path.Replace("\\", "/");
            root = root.Replace("\\", "/");
            root = string.IsNullOrWhiteSpace(root) ? ConfigHelper.Config.DefaultPath : root;

            if (path == "" | !path.StartsWith(root))
            {
                path = root;
            }
            try
            {
                DataTable tab = FileHelper.GetFile(context.Server.MapPath(path));
                StringBuilder sb = new StringBuilder(string.Empty);
                for (int i = 0; i < tab.Rows.Count; i++)
                {
                    string name = tab.Rows[i]["Name"].ToString();
                    string onclick = "FileManger.selectSingleFile(this);";  //绑定点击事件
                    string p = path.EndsWith("/") ? path + name : path + "/" + name;
                    string type = "file";

                    string icon = FileHelper.GetIcon(context.Server.MapPath(p), p);

                    if (tab.Rows[i]["Type"].ToString() == FileHelper.FOLDER)
                    {
                        onclick = "FileManger.getFileList(\"" + p + "\");";
                        type = "folder";
                    }
                    sb.Append(string.Format(FILIST_FORMAT, icon, name, name, name, p, onclick, type));
                }
                m.Code = 0;
                m.Success = true;
                m.O = new { BackPath = FileHelper.GetFatherDirectoryPath(path), FileList = sb.ToString() };
                return m;
            }
            catch (Exception ex)
            {
                m.Code = 1;
                m.Success = false;
                m.Message = ex.Message;
                return m;
            }
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private SysMessage FiUploader(HttpContext context)
        {
            SysMessage m = new SysMessage();
            int t;
            string root = context.Request.Form["p"] == null ? "" : context.Request.Form["p"].Trim();            //保存路径
            string id = context.Request.Form["id"] == null ? "" : context.Request.Form["id"].Trim();            //控件名
            int mode = context.Request.Form["m"] == null ? 0 : int.TryParse(context.Request.Form["m"].Trim(), out t) ? t : 0;   //保存模式

            //检查保存路径
            if (root == "")
            {
                m.Code = 1;
                m.Success = false;
                m.Message = "保存路径为空!";
                return m;
            }
            else
            {
                root = root.Replace("\\", "/");
            }
            //检查控件名
            if (id == "")
            {
                m.Code = 2;
                m.Success = false;
                m.Message = "file控件名为空!";
                return m;
            }
            //获得file控件
            HttpPostedFile file = context.Request.Files[id];

            //检查控件是否为空
            if (file == null)
            {
                m.Code = 3;
                m.Success = false;
                m.Message = "名为" + id + "的file控件为空！";
                return m;
            }
            string fileName = file.FileName;        //文件原名

            //检查文件名是否为空
            if (string.IsNullOrWhiteSpace(fileName))
            {
                m.Code = 4;
                m.Success = false;
                m.Message = "文件为空！";
                return m;
            }
            //检查文件是否有扩展名
            if (!Path.HasExtension(fileName))
            {
                m.Code = 5;
                m.Success = false;
                m.Message = "文件格式有误！";
                return m;
            }

            string fileExtension = Path.GetExtension(fileName).ToLower();   //获得文件扩展名

            //检查保存路径是否有误
            try
            {
                string p1 = root.EndsWith("/") ? root + (mode == 0 ? DateTime.Now.ToString(TIME_FORMAT1) + "/" : "") : root + "/" + (mode == 0 ? DateTime.Now.ToString(TIME_FORMAT1) + "/" : "");   //获得文件保存url路径
                string filePath = context.Server.MapPath(p1);       //文件保存的物理路径

                //如果目标文件夹不存在，自动新建文件夹
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }

                string name = BizHelper.GetSerial(1) + fileExtension;   //新文件名
                file.SaveAs(filePath + name);                           //保存文件
                string p = p1 + name;                                   //新文件url               

                object[] os = new object[1];
                os[0] = new { Url = p, Name = name, Icon = FileHelper.GetIcon(context.Server.MapPath(p), p) };
                m.Code = 0;
                m.Success = true;
                m.O = new { OS = os };
            }
            catch (Exception ex)
            {
                m.Code = 6;
                m.Success = false;
                m.Message = ex.Message;
            }
            return m;
        }

        /// <summary>
        /// 新建文件夹
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private SysMessage NewFolder(HttpContext context)
        {
            SysMessage m = new SysMessage();
            string path = context.Request.Form["path"] == null ? "" : context.Request.Form["path"].Trim();  //保存路径
            string name = context.Request.Form["name"] == null ? "" : context.Request.Form["name"].Trim();  //文件夹名
            if (path == "")
            {
                m.Code = 1;
                m.Success = false;
                m.Message = "文件路径有误！";
                return m;
            }
            if (name == "")
            {
                m.Code = 2;
                m.Success = false;
                m.Message = "文件夹名为空！";
                return m;
            }

            string folderPath = path.EndsWith("/") ? path + name : path + "/" + name;

            DirectoryInfo di = new DirectoryInfo(context.Server.MapPath(folderPath));
            if (di.Exists)
            {
                m.Code = 3;
                m.Success = false;
                m.Message = "该路径下存在同名文件夹!";
                return m;
            }

            try
            {
                di.Create();
                m.Code = 0;
                m.Success = true;
                m.O = new { fpath = string.Format(FILIST_FORMAT2, FileHelper.GetIcon(context.Server.MapPath(folderPath), folderPath), name, name, name, folderPath, "href='?p=" + folderPath + "'") };

            }
            catch (Exception ex)
            {
                m.Code = 4;
                m.Success = false;
                m.Message = ex.Message;
            }

            return m;
        }

        /// <summary>
        /// 检查文件夹
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private SysMessage CheckFolder(HttpContext context)
        {
            SysMessage m = new SysMessage();

            string p = context.Request.Form["p"] == null ? "" : context.Request.Form["p"].Trim();
            if (p == "")
            {
                m.Code = 1;
                m.Success = false;
                m.Message = "文件路径为空！";
                return m;
            }

            //获得文件/文件夹的完整物理路径

            string fullPath = context.Server.MapPath(p);
            //如果是文件，直接返回成功
            if (File.Exists(fullPath))
            {
                m.Code = 0;
                m.Success = true;
                return m;
            }

            try
            {
                //创建文件夹实例
                DirectoryInfo di = new DirectoryInfo(fullPath);

                //如果文件夹不存在，返回错误信息
                if (!di.Exists)
                {
                    throw new Exception("文件夹不存在！");
                }
                //如果文件夹下包含文件或子文件夹，给出提示信息
                if (di.GetDirectories().Length > 0 || di.GetFiles().Length > 0)
                {
                    m.Code = 0;
                    m.Success = true;
                    m.Message = "目录下存在子目录或子文件,您确定要删除该文件夹吗！";
                }
                else
                {
                    m.Code = 0;
                    m.Success = true;
                }
            }
            catch (Exception ex)
            {
                m.Code = 2;
                m.Success = false;
                m.Message = ex.Message;

            }
            return m;
        }

        /// <summary>
        /// 多文件上传
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private SysMessage FiUploaderM(HttpContext context)
        {
            SysMessage m = new SysMessage();
            int t;
            string root = context.Request.Form["p"] == null ? "" : context.Request.Form["p"].Trim();        //保存路径
            string id = context.Request.Form["id"] == null ? "" : context.Request.Form["id"].Trim();        //获取控件名
            int mode = context.Request.Form["m"] == null ? 0 : int.TryParse(context.Request.Form["m"].Trim(), out t) ? t : 0;   //获取上传模式
            //检查保存路径
            if (root == "")
            {
                m.Code = 1;
                m.Success = false;
                m.Message = "保存路径为空!";
                return m;
            }
            else
            {
                root = root.Replace("\\", "/");
            }

            //检查空间名
            if (id == "")
            {
                m.Code = 2;
                m.Success = false;
                m.Message = "file控件名为空!";
                return m;
            }

            object[] os = new object[context.Request.Files.Count];

            try
            {
                //循环保存文件
                for (int i = 0; i < context.Request.Files.Count; i++)
                {
                    HttpPostedFile file = context.Request.Files[i];
                    if (!string.IsNullOrWhiteSpace(file.FileName))
                    {
                        string fileName = Path.GetFileName(file.FileName);  //上传文件的原名
                        string fileExtension = Path.GetExtension(fileName).ToLower();   //文件扩展名
                        string p1 = root.EndsWith("/") ? root + (mode == 0 ? DateTime.Now.ToString(TIME_FORMAT1) + "/" : "") : root + "/" + (mode == 0 ? DateTime.Now.ToString(TIME_FORMAT1) + "/" : "");    //文件保存路径
                        string filePath = context.Server.MapPath(p1);   //文件保存的物理路径
                        
                        //如果目标目录不存在，自动创建目录
                        if (!Directory.Exists(filePath))
                        {
                            Directory.CreateDirectory(filePath);
                        }
                        string name = BizHelper.GetSerial(4) + fileExtension;   //新文件名
                        file.SaveAs(filePath + name);                           //保存文件
                        string p = p1 + name;                                   //新文件url
                        os[i] = new { Url = p, Name = name, Icon = FileHelper.GetIcon(context.Server.MapPath(p), p) };      //添加新文件信息对象
                    }
                }
                m.Code = 0;
                m.Success = true;
                m.O = new { OS = os };
            }
            catch (Exception ex)
            {
                m.Code = 3;
                m.Success = false;
                m.Message = ex.Message;
            }

            return m;
        }
        #endregion
    }
}